<template>
  <div class="userinfo-container" v-if="userInfo" v-loading="state.userLoading">
    <header class="userinfo-header">账号信息</header>
    <body class="userinfo-body">
      <!-- 头像 -->
      <section class="info-item avatar-item">
        <span class="label">头像</span>
        <upload class="info-box" action="/upload" :cicle="true" :on-success="onSuccess">
          <img
            style="max-width: 100%; max-height: 100%"
            :src="userInfo.avatar ? userInfo.avatar : state.defaultAvatar"
            class="avatar"
          />
        </upload>
        <!-- <div class="info-box">
          <img :src="userInfo.avatar || state.defaultAvatar" alt="" class="avatar" />
        </div> -->
        <div class="actions">
          <!-- 头像 -->
          <!-- <FileUpload
              ref="modifyAvatar"
              :files="state.preloadAvatar"
              :multiple="false"
              :fileTypeList="['bmp', 'jpg', 'png', 'gif', 'jpeg', 'cdr', 'psd']"
              @extra-files="onFileUpload"
              :fileAccept="'image/*'"
            ></FileUpload> -->
        </div>
      </section>
      <!-- 用户名 -->
      <section class="info-item name-item">
        <span class="label">用户名</span>
        <div class="info-box">
          <el-input
            v-model="state.modifyName"
            placeholder="请输入用户名"
            clearable
            v-if="state.isModifyName"
          ></el-input>
          <p class="text" v-else>{{ userInfo.userName ? userInfo.userName : userInfo.userName }}</p>
        </div>
        <div class="actions">
          <template v-if="state.isModifyName">
            <a href="javascript:;" class="cancel" @click="onCancelName">取消</a>
            <a href="javascript:;" @click="onSaveName">保存</a>
          </template>
          <a href="javascript:;" @click="toModifyName" v-else>编辑</a>
        </div>
      </section>
      <!-- 密码 -->
      <section class="info-item">
        <span class="label">密码</span>
        <div class="info-box">
          <p class="text password">········</p>
        </div>
        <div class="actions">
          <a href="javascript:;" @click="state.showModifyPassword = true">修改</a>
        </div>
      </section>
      <!-- 手机号 -->
      <!-- <section class="info-item name-item">
        <span class="label">手机号</span>
        <div class="info-box">
          <el-input
            v-model="state.modifyPhone"
            placeholder="请输入用户名"
            clearable
            v-if="state.isModifyPhone"
          ></el-input>
          <p class="text" v-else>{{ replacePhone(userInfo.phone) }}</p>
        </div>
        <div class="actions">
          <template v-if="state.isModifyPhone">
            <a href="javascript:;" class="cancel" @click="onCancelPhone">取消</a>
            <a href="javascript:;" @click="onSavePhone">保存</a>
          </template>
          <a href="javascript:;" v-else @click="toModifyPhone">修改</a>
        </div>
      </section> -->
    </body>
    <!-- 修改密码 -->
    <el-dialog
      title="修改密码"
      v-model="state.showModifyPassword"
      width="400px"
      destroy-on-close
      :before-close="onClose"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="ruleFormRef" :model="state.modifyPasswordForm" :rules="state.rules">
        <el-form-item label="当前密码" prop="passWord">
          <el-input
            v-model="state.modifyPasswordForm.passWord"
            placeholder="请输入当前密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassWord">
          <el-input
            v-model="state.modifyPasswordForm.newPassWord"
            placeholder="密码长度8-16位,必须包含数字和字母!"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassWord">
          <el-input
            v-model="state.modifyPasswordForm.confirmPassWord"
            placeholder="请确认新密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="onClose()" v-if="!state.forcedPassword">取 消</el-button>
        <el-button type="warning" @click="onBackLogin" v-else>返回登录</el-button>
        <el-button color="#6C52EA" @click="onModifyPassword">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
// import FileUpload from '@/utils/FileUpload/FileUpload.vue'
import upload from '@/components/Upload'
import { editUserData, getUserList } from '@/apis/system/userInfo'
import { editPassWord } from '@/apis/login/login'
import { ElMessage } from 'element-plus'
import { Itype } from '@/type'
import Bus from '@/utils/bus'
import { dataInterface } from '@/apis/login/login'
import { useRouter } from 'vue-router'
import useCurrentInstance from '@/utils/useCurrentInstance'
const router = useRouter()
import { getCurrentInstance } from 'vue'
import md5 from 'js-md5' //导入
const { proxy } = getCurrentInstance() as any
proxy.$md5 = md5 //md5转换为vue原型
/* eslint-disable */
const checkNewPassword = (rule: object /*  */, value: string, callback: Function) => {
  const reg = /^(?=.*[0-9\!@#\$%\^&\*])(?=.*[a-zA-Z]).{8,16}$/
  if (!value) {
    callback(new Error('请输入新密码!'))
  } else if (!reg.test(value)) {
    callback(new Error('密码由数字、字母、特殊字符组成,长度8-16位,必须包含数字和字母!'))
  } else {
    callback()
  }
}
const checkConfirmPassword = (rule: object, value: string, callback: Function) => {
  if (!value) {
    callback(new Error('请确认新密码!'))
  } else if (value !== state.modifyPasswordForm.newPassWord) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
const state = reactive({
  defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  userLoading: false,
  preloadAvatar: [],
  // 用户名
  isModifyName: false,
  modifyName: '',
  // 修改密码
  showModifyPassword: false,
  modifyPasswordForm: {
    passWord: '',
    newPassWord: '',
    confirmPassWord: ''
  },
  forcedPassword: 0,
  rules: {
    password: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { validator: checkNewPassword, trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { validator: checkConfirmPassword, trigger: 'blur' }
    ]
  },
  // 手机号
  isModifyPhone: false,
  // 修改手机号码
  modifyPhone: ''
})
/**
 * @desc: 手机号处理
 */
const replacePhone = (phone: string) => {
  if (phone) {
    return phone.toString().replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }
  return ''
}
/**
 * @desc: 取消编辑手机号
 */
const onCancelPhone = () => {
  state.modifyPhone = ''
  state.isModifyPhone = false
}
/**
 *
 * @desc:获取登录用户信息
 */
let userInfo: Itype = ref({})
const getUserInfo = () => {
  userInfo.value = proxy.$GetUserInfo()
  if (router.currentRoute.value.query.unBackFlag) {
    state.showModifyPassword = true
  }
}
getUserInfo()
/**
 * @desc:上传头像图片
 */
const onFileUpload = (data: Itype) => {
  if (!data || !data.length) return
  const file = data[data.length - 1]
  modifyInfo({
    avatar: file?.url,
    id: userInfo.value.id
  })
  state.preloadAvatar = []
}
/**
 * @desc: 拼接图片路径
 */
const API_BASE_URL = 'http://localhost:3008'
const onSuccess = (res: any) => {  
  //拼装图片路径赋值给表单
  userInfo.value.avatar = API_BASE_URL + '/' + res.path.slice(0, 7) + '/' + res.path.slice(8)
  modifyInfo({
    id: userInfo.value.id,
    avatar: userInfo.value.avatar
  })
}
/**
 * @desc: 提交编辑
 * @param {Object} params 参数
 */
const modifyInfo = (params: Itype) => {
  state.userLoading = true
  editUserData(params)
    .then((res: Itype) => {
      if (res) {
        ElMessage.success('操作成功！')
        refreshUserInfo()
      }
      state.userLoading = false
    })
    .catch((err) => {
      console.log(err)
      state.userLoading = false
      ElMessage.error('服务器内部错误！')
    })
}
/**
 * @desc: 刷新用户信息
 */
const refreshUserInfo = () => {
  state.userLoading = true
  getUserList({
    user_id: userInfo.value.id
  }).then((res: Itype) => {
    if (!res) return
    const { avatar, userName } = res || {}
    localStorage.setItem(
      'user',
      JSON.stringify({
        ...userInfo.value,
        avatar: res[0].avatar,
        userName: res[0].userName
      })
    )
    userInfo.value = proxy.$GetUserInfo()
    Bus.emit('updateUserInfo')
    state.userLoading = false
  })
}
/**
 * @desc: 取消编辑名称
 */
const onCancelName = () => {
  state.isModifyName = false
  state.modifyName = ''
}
/**
 * @desc: 编辑名称
 */
const onSaveName = () => {
  modifyInfo({
    id: userInfo.value.id,
    userName: state.modifyName
  })
  onCancelName()
}
/**
 * @desc: 前往编辑名称
 */
const toModifyName = () => {
  state.modifyName = userInfo.value.name || ''
  state.isModifyName = true
}
/**
 * @desc: 取消修改密码
 */
interface Ipassword {
  password: string
  newPassword: string
  confirmPassword: string
}
let modifyPasswordForm = ref<Ipassword>()
const onClose = () => {
  modifyPasswordForm.value = {
    password: '',
    newPassword: '',
    confirmPassword: ''
  }
  state.showModifyPassword = false
}
/**
 * @desc: 返回登陆
 */
const onBackLogin = () => {
  router.replace({
    name: 'Login'
  })
}
/**
 * @desc: 提交修改密码
 */
const ruleFormRef = ref()
const onModifyPassword = () => {
  ruleFormRef.value.validate((valid: boolean) => {
    if (!valid) return false
    state.userLoading = true
    editPassWord({
      id: userInfo.value.id,
      passWord: proxy.$md5(state.modifyPasswordForm.passWord),
      newPassWord: proxy.$md5(state.modifyPasswordForm.newPassWord),
      confirmPassWord: proxy.$md5(state.modifyPasswordForm.confirmPassWord),
    })
      .then((res) => {
        state.userLoading = false
        if (res) {
          localStorage.setItem('updatePwd', '1')
          state.showModifyPassword = false
          ElMessage.success('修改成功！即将自动跳转到登录页重新登录！')
          setTimeout(() => {
            router.replace({
              name: 'Login'
            })
          }, 1500)
          return
        } else {
          ElMessage.error('操作失败1！')
        }
      })
      .catch((err) => {
        console.log(err)
        state.userLoading = false
        ElMessage.error('操作失败！')
      })
  })
}
/**
 * @desc: 保存手机号
 */
const onSavePhone = () => {
  const phoneReg =
    /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(19[0-9]{1})|(18[0-9]{1}))+\d{8})$/
  if (!phoneReg.test(state.modifyPhone)) {
    ElMessage.warning('请输入正确手机号')
    return
  }
  modifyInfo({
    id: userInfo.value.id,
    phone: state.modifyPhone
  })
  onCancelPhone()
}
/**
 * @desc: 手机号
 */
const toModifyPhone = () => {
  state.isModifyPhone = true
  state.modifyPhone = userInfo.value.phone || ''
}
/**
 * @desc: 解除绑定
 */
const onRelieve = () => {
  state.userLoading = true
  let archiType = ref(0)
  const typeString = proxy.$GetTargetArchi('archiType')
  if (typeString === 'project') {
    archiType.value = 2
  } else if (typeString === 'company') {
    archiType.value = 1
  } else {
    state.userLoading = false
    ElMessage.error('操作失败！')
    return
  }
  dataInterface(
    {
      archiID: proxy.$GetTargetArchi('archiId'),
      archiType,
      user_id: userInfo.value.id
    },
    'api/wechat/deleteSync',
    'DELETE'
  )
    .then((res) => {
      state.userLoading = false
      if (res.code === 200) {
        ElMessage.success('已解除企业微信绑定')
        refreshUserInfo()
      } else {
        ElMessage.error('操作失败！')
      }
    })
    .catch((err) => {
      console.log(err)
      state.userLoading = false
      ElMessage.error('操作失败！')
    })
    .catch(() => {})
}
</script>

<style lang="less" scoped>
@itemHeight: 46px;
.userinfo-container {
  width: 80%;
  margin-left: 24px;
  background: #ffffff;
  border-radius: 8px;
  .userinfo-header {
    width: 100%;
    height: 48px;
    padding: 0 24px;
    box-sizing: border-box;
    background: #ffffff;
    border-bottom: 1px solid #f2f4f7;
    color: #2a2f3d;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    font-size: 14px;
    line-height: 48px;
  }

  .userinfo-body {
    width: 100%;
    height: 100%;
    padding: 24px 40px;
    box-sizing: border-box;
    .info-item {
      display: flex;
      align-items: center;
      width: 100%;
      min-height: @itemHeight;
      margin-top: 24px;
      &.avatar-item {
        .label {
          line-height: 56px;
        }
        .actions a {
          display: block;
          height: 56px;
          line-height: 62px;
        }
      }
      .info-box {
        box-sizing: border-box;
        padding: 0 24px;
        flex: 1;
        min-height: 22px;
        .text {
          color: #121619;
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          line-height: 22px;
          &.password {
            font-weight: bold;
            font-size: 26px;
            letter-spacing: -4px;
          }
        }
        .avatar {
          height: 56px;
          width: 56px;
        }
      }
      .actions {
        width: auto;
        min-height: 22px;
        box-sizing: border-box;
        a {
          color: #0076ff;
          font-size: 12px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          line-height: 22px;
          &.cancel {
            color: #4d5358;
          }
          &.modify-avatar {
            position: relative;
            overflow: hidden;
            .file-upload {
              overflow: hidden;
              position: absolute;
              top: 0;
              left: 0;
              height: 100%;
              width: 100%;
              padding: 0;
              opacity: 0;
            }
          }
        }
        a + a {
          margin-left: 10px;
        }
      }
    }
  }
}
@media (max-width: 1000px) {
  .userinfo-container {
    width: 100%;
    margin-left: 0;
  }
}
</style>
